// e50.groovy
// http://projecteuler.net/index.php?section=problems&id=50
/*

The prime 41, can be written as the sum of six consecutive primes:

41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most consecutive primes?

*/

primes = new File("primes.txt").readLines().collect { e -> e.toBigInteger() }
println "Loaded ${primes.size()} prime numbers less than one million."

primes = primes[0..1230]

lastIndex = primes.size() - 1
startingPrime = 2
startingIndex = 0
mostTerms = 1
maxTotal = 0
limit = 1000000

for (start in 0..lastIndex) {
    println "Starting with primes[${start}] (${primes[start]})" 
    def sum = primes[start..lastIndex].sum()
    def end = lastIndex
    while (sum >= limit || !sum.isProbablePrime(2))  {
        sum -= primes[end--]
        if ((end-start) <= mostTerms) { break }
    }
    if ((end-start) > mostTerms) {
        mostTerms = end-start + 1
        maxTotal = sum
        startingPrime = primes[start]
        startingIndex = start
        println "new series of ${mostTerms} terms starting with primes[${start}] (${primes[start]}): ${maxTotal}"
    }
}

println "terms: ${mostTerms} sum: ${maxTotal} start Index: ${startingIndex} start prime: ${startingPrime}"
